package org.hfy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hfy.common.ApiResponse;
import org.hfy.dto.ContractAuditDTO;
import org.hfy.dto.ContractQueryDTO;
import org.hfy.entity.Contract;
import org.hfy.entity.Quotation;
import org.hfy.service.ContractService;
import org.hfy.service.QuotationService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 合同控制器
 * 
 * @author hfy
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/contracts")
@RequiredArgsConstructor
@Validated
public class ContractController {

    private final ContractService contractService;
    private final QuotationService quotationService;

    /**
     * 分页查询合同列表
     */
    @GetMapping
    public ApiResponse<IPage<Contract>> getContractPage(ContractQueryDTO query) {
        IPage<Contract> page = contractService.getContractPage(query);
        return ApiResponse.success(page);
    }

    /**
     * 根据ID查询合同详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Contract> getContractById(@PathVariable Long id) {
        log.info("=== Controller层调试：开始获取合同详情，合同ID: {} ===", id);
        
        // 先获取基本合同信息
        Contract contract = contractService.getContractWithQuotationById(id);
        log.info("Controller层调试：获取到合同信息，合同号: {}, 报价单ID: {}", 
                contract != null ? contract.getContractNo() : "null",
                contract != null ? contract.getQuotationId() : "null");
        
        // 检查报价单信息
        if (contract != null && contract.getQuotation() != null) {
            log.info("Controller层调试：报价单信息存在，报价单号: {}, items: {}", 
                    contract.getQuotation().getQuotationNo(),
                    contract.getQuotation().getItems() != null ? contract.getQuotation().getItems().size() + "个物料" : "null");
            
            // 如果items为null，手动重新获取
            if (contract.getQuotation().getItems() == null && contract.getQuotationId() != null) {
                log.warn("Controller层调试：发现items为null，手动重新获取报价单详情");
                
                Quotation fullQuotation = quotationService.getQuotationWithItemsById(contract.getQuotationId());
                log.info("Controller层调试：重新获取报价单，items数量: {}", 
                        fullQuotation != null && fullQuotation.getItems() != null ? fullQuotation.getItems().size() : "仍为null");
                
                if (fullQuotation != null) {
                    contract.setQuotation(fullQuotation);
                    log.info("Controller层调试：已重新设置报价单信息");
                }
            }
        } else {
            log.warn("Controller层调试：合同或报价单信息为空");
        }
        
        log.info("=== Controller层调试：合同详情获取完成 ===");
        return ApiResponse.success(contract);
    }

    /**
     * 合同审核
     */
    @PostMapping("/{id}/audit")
    public ApiResponse<String> auditContract(@PathVariable Long id, @Valid @RequestBody ContractAuditDTO auditDTO) {
        boolean result = contractService.auditContract(id, auditDTO);
        if (result) {
            return ApiResponse.success("合同审核成功");
        } else {
            return ApiResponse.error("合同审核失败");
        }
    }

    /**
     * 预览合同HTML
     */
    @GetMapping("/{id}/preview")
    public ResponseEntity<String> previewContractHtml(@PathVariable Long id) {
        try {
            log.info("开始预览合同HTML，合同ID: {}", id);
            String htmlContent = contractService.generateContractHtml(id);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_HTML);
            headers.add("Content-Type", "text/html; charset=UTF-8");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(htmlContent);
        } catch (Exception e) {
            log.error("预览合同HTML失败，合同ID: {}", id, e);
            String errorHtml = generateErrorHtml("预览合同失败: " + e.getMessage());
            return ResponseEntity.ok()
                    .header("Content-Type", "text/html; charset=UTF-8")
                    .body(errorHtml);
        }
    }

    /**
     * 下载合同PDF
     */
    @GetMapping("/{id}/download")
    public ResponseEntity<byte[]> downloadContractPdf(@PathVariable Long id) {
        try {
            log.info("开始下载合同PDF，合同ID: {}", id);
            byte[] pdfBytes = contractService.downloadContractPdf(id);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", "contract_" + id + ".pdf");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
        } catch (Exception e) {
            log.error("下载合同PDF失败，合同ID: {}", id, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 调试：查看报价单原始数据
     */
    @GetMapping("/debug/quotation/{quotationId}")
    public ApiResponse<Object> debugQuotation(@PathVariable Long quotationId) {
        try {
            // 直接调用 quotationService 获取数据
            Quotation quotation = quotationService.getQuotationWithItemsById(quotationId);
            
            Map<String, Object> debugInfo = new HashMap<>();
            debugInfo.put("quotation", quotation);
            debugInfo.put("quotationId", quotationId);
            debugInfo.put("hasItems", quotation != null && quotation.getItems() != null);
            debugInfo.put("itemsCount", quotation != null && quotation.getItems() != null ? quotation.getItems().size() : 0);
            debugInfo.put("itemsDetails", quotation != null ? quotation.getItems() : null);
            
            return ApiResponse.success(debugInfo);
        } catch (Exception e) {
            log.error("调试查看报价单原始数据失败: {}", e.getMessage(), e);
            return ApiResponse.error("查看数据失败: " + e.getMessage());
        }
    }

    /**
     * 生成错误HTML页面
     * 
     * @param errorMessage 错误信息
     * @return 错误HTML内容
     */
    private String generateErrorHtml(String errorMessage) {
        return "<!DOCTYPE html>" +
                "<html lang=\"zh-CN\">" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                "<title>合同预览错误</title>" +
                "<style>" +
                "body { font-family: 'Microsoft YaHei', sans-serif; padding: 50px; text-align: center; background: #f5f5f5; }" +
                ".error-container { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); max-width: 600px; margin: 0 auto; }" +
                ".error-title { color: #e74c3c; font-size: 24px; margin-bottom: 20px; }" +
                ".error-message { color: #7f8c8d; font-size: 16px; line-height: 1.6; margin-bottom: 30px; }" +
                ".error-tip { color: #95a5a6; font-size: 14px; }" +
                "</style>" +
                "</head>" +
                "<body>" +
                "<div class=\"error-container\">" +
                "<div class=\"error-title\">合同预览失败</div>" +
                "<div class=\"error-message\">抱歉，合同预览过程中出现错误：<br>" + errorMessage + "</div>" +
                "<div class=\"error-tip\">请联系系统管理员或稍后重试</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }
} 